//
//  YREmotionTools.swift
//  新浪微博
//
//  Created by Viper on 16/7/5.
//  Copyright © 2016年 Viper. All rights reserved.
//

import UIKit
//显示的列数
let emotionsMaxCol = 7
//显示的行数
let emotionsMaxRow = 3
//每页显示的个数
let emitionsMaxCount = emotionsMaxCol * emotionsMaxRow - 1
class YREmotionTools: NSObject {
    
    //全局访问点
    static let sharedTools : YREmotionTools = YREmotionTools()
    
 
    //获得bundle
    lazy var emotionBundle : NSBundle = {
        //获取bundle路径
       let path = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)!
        //返回bundle
        return NSBundle(path: path)!
    }()
    
    //default 表情一维数组
    lazy  var defaultEmotions :[YREmotion] = {
        
        return self.getEmotions("default/")
    }()
    //emoji 表情一维数组
    lazy  var emojiEmotions :[YREmotion] = {
        
        return self.getEmotions("emoji/")
    }()
    //lxh 表情一维数组
    lazy  var lxhEmotions :[YREmotion] = {
        
        return self.getEmotions("lxh/")
    }()

    //三维数组
    lazy var allEmotions : [[[YREmotion]]] = {
        
       return [
        
        self.getEmotionsGroup(self.defaultEmotions),
        self.getEmotionsGroup(self.emojiEmotions),
        self.getEmotionsGroup(self.lxhEmotions)
        
        ]     
    }()

    //读取plist文件中的数组转成模型一维数组
    func getEmotions(fileName : String)->[YREmotion]{
        //路径
        let file = emotionBundle.pathForResource("\(fileName)info.plist", ofType: nil)!
        //plist转数组
        let array = NSArray(contentsOfFile: file)!
        //创建可变的临时数组
        var tempArray : [YREmotion] = [YREmotion]()
        
        //遍历数组
        for dict in array {
            
            let e = YREmotion(dict: dict as! [String : AnyObject])
            
            //获取路径
            
            e.path = "\(fileName)"
            
            //保存模型
            tempArray.append(e)
            
        }
        //返回数组
        return tempArray
        
    }
    //一维数组 转二维数组
    func getEmotionsGroup(emotions : [YREmotion])->[[YREmotion]]{
        //页数 =（emotions数量+20-1）/20
        let pageCount = (emotions.count + emitionsMaxCount - 1 )/emitionsMaxCount
        //创建临时可变的二维数组
        var tempArray : [[YREmotion]] = [[YREmotion]]()
        
        //.enumerate() 正序遍历     .reverse() 倒序遍历
        //遍历
        for i in 0..<pageCount{
            //位置和长度
            let loc = emitionsMaxCount * i
            var len = emitionsMaxCount
            //默认表情数组越界
            if loc + len > emotions.count {
                //一维数组的数量 减去 位置
                len = emotions.count - loc
                
            }
            //截取范围
            let range = NSMakeRange(loc, len)
            //数组的截取
          let arr =  (emotions as NSArray).subarrayWithRange(range) as! [YREmotion]

           //保存一维数组
            
            tempArray.append(arr)
            
        }
        //返回二维数组
        return tempArray
    }

}
